package com.mstarc.app.mnfc;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.mstarc.app.mnfc.mstarcApiUtils.ApduUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.BytetohexStringUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.CloseUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.InitSEIDUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.InitializeUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.MstarcInitUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.MstarcResetUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.SelectUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.StringAndByteUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.SwitchModeUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.WriteSEIDUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

import mstarc_os_api.mstarc_os_api_msg;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    //    private static final String URL = "http://wxtest.qdyouke.online/GetCreateSSDApdu.aspx?";
    private static final String IP = "http://115.29.105.115:8199/";
    private static final String IP1 = "http://natapp.qdyouke.com/GetApduList.aspx?";
    //http://junfu.qdyouke.com
    /*下载apdu安装包*/
    private static final String APDU_URL = IP + "GetAppApdu.aspx?";
    /*创建SSD*/
    private static final String SSD_URL = IP + "GetCreateSSDApdu.aspx?";
    /*充值*/
    private static final String PERSONALIZE_URL = IP + "GetChongZhiApdu.aspx?";
    private static final String KEYI_URL = IP + "GetKeYiApdu.aspx?";

    private static final String FIRSTREQUESTSTR = "&start=1";
    private static final String SEID_STR = "&seId=";
    private static final String APPSERIAL = "&appSerial=";//卡号
    private static final String BALANCE = "&balance=";//余额
    private static final String CHARGECOUNT = "&chargeCount=10000";//充值金额
    private static final String LASTRECORD = "&lastRecord=";//最后一次交易记录
    private static final String LASTAPDU = "&lastApdu=";//最后一次请求的apdu指令
    private static final String LASTDATA = "&lastData=";
    private static final String APDUNUM = "&apduSum=";
    private static final String LASTAPDUSW = "&lastApduSw=";
    private static final String SZT = "szt";
    private static final String TC = "tc";
    private static final String BJ = "bj";
    private static final int TYPE_SZT = 10001;//对应深圳通“szt”
    private static final int TYPE_TC = 10002;//对应太仓“tc”
    private static final int TYPE_BJ = 10003;//对应北京“bj”
    private static final int URL_TYPE_PERSONALIZE = 20001;
    private static final int URL_TYPE_KEYI = 10002;
    private static final String TYPE = "&type=";
    private static final String TAG = "MainActivity";
    private Button btn_init,
            btn_reset,
            btn_send,
            btn_close,
            btn_change,
            btn_seid,
            btn_create_ssd,
            btn_personalize,
            btn_create_ssd_tc,
            btn_send_tc,
            btn_read_code,
            btn_reset_apdu,
            btn_create_ssd_bj,
            btn_apdu_bj,
            btn_recharge_szt,
            btn_read_code_tc,
            btn_recharge_tc,
            btn_keyi_szt,
            btn_keyi_tc,
            btn_change_app_szt,
            btn_change_app_tc,
            btn_duandian,
            btn_action;
    private TextView tv_res;
    private mstarc_os_api_msg m_api_msg;
    private Context mContext;
    private boolean hasConnected;//是否已经初始化
    //00 c0 00 00 XX
    int[] secondApdu = new int[]{0x00, 0xc0, 0x00, 0x00, 0x00};
    private int count = 0;//记录第几次网络请求
    private int apduSum = 0;//apdu请求中9000的个数
    private String seid = "";//seid 17003077040147350426
    private String URL = "";//网络请求的接口地址前缀
    private RequestTypeEnum requestTypeEnum;//当前网络请求的类型
    private String mType = "";//记录当前的请求类型（深圳通，太仓）
    private int mTypeInt = 0;
    private String mCode = "";//卡号
    private String mBalance = "";//余额
    private String mChargeCount = "";//充值金额
    private String mLastRecord = "";//最后一条交易记录
    private String mLastApdu = "";//每次请求执行的最后一条apdu指令
    private String mCity = "";//城市代码（TC）
    private boolean isPersonalize = false;
    private int urlType = 0;
    private String lastData = "";
    private int[] lastApduSw = new int[2];
    private int httpT = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initView();
        m_api_msg = InitializeUtil.getInstance(mContext).getM_api_msg();
        startService(new Intent(MainActivity.this, ApduService.class));
    }

    @Override
    protected void onDestroy() {
//        stopService(new Intent(MainActivity.this, ApduService.class));
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        if (m_api_msg != null) {
            int i = CloseUtil.closeMstarcApi(m_api_msg);
            startLog("resume关闭：", i + "");
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        toDuandian();
    }

    private void initView() {
        tv_res = (TextView) findViewById(R.id.tv_res);
        btn_init = (Button) findViewById(R.id.btn_init);
        btn_reset = (Button) findViewById(R.id.btn_reset);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_close = (Button) findViewById(R.id.btn_close);
        btn_change = (Button) findViewById(R.id.btn_change);
        btn_seid = (Button) findViewById(R.id.btn_seid);
        btn_create_ssd = (Button) findViewById(R.id.btn_create_ssd);
        btn_personalize = (Button) findViewById(R.id.btn_personalize);
        btn_create_ssd_tc = (Button) findViewById(R.id.btn_create_ssd_tc);
        btn_send_tc = (Button) findViewById(R.id.btn_send_tc);
        btn_read_code = (Button) findViewById(R.id.btn_read_code);
        btn_reset_apdu = (Button) findViewById(R.id.btn_reset_apdu);
        btn_create_ssd_bj = (Button) findViewById(R.id.btn_create_ssd_bj);
        btn_apdu_bj = (Button) findViewById(R.id.btn_apdu_bj);
        btn_recharge_szt = (Button) findViewById(R.id.btn_recharge_szt);
        btn_read_code_tc = (Button) findViewById(R.id.btn_read_code_tc);
        btn_recharge_tc = (Button) findViewById(R.id.btn_recharge_tc);
        btn_keyi_szt = (Button) findViewById(R.id.btn_keyi_szt);
        btn_keyi_tc = (Button) findViewById(R.id.btn_keyi_tc);
        btn_change_app_szt = (Button) findViewById(R.id.btn_change_app_szt);
        btn_change_app_tc = (Button) findViewById(R.id.btn_change_app_tc);
        btn_duandian = (Button) findViewById(R.id.btn_duandian);
        btn_action = (Button) findViewById(R.id.btn_action);
        btn_init.setOnClickListener(this);
        btn_reset.setOnClickListener(this);
        btn_send.setOnClickListener(this);
        btn_close.setOnClickListener(this);
        btn_change.setOnClickListener(this);
        btn_create_ssd.setOnClickListener(this);
        btn_seid.setOnClickListener(this);
        btn_personalize.setOnClickListener(this);
        btn_create_ssd_tc.setOnClickListener(this);
        btn_send_tc.setOnClickListener(this);
        btn_read_code.setOnClickListener(this);
        btn_reset_apdu.setOnClickListener(this);
        btn_create_ssd_bj.setOnClickListener(this);
        btn_apdu_bj.setOnClickListener(this);
        btn_recharge_szt.setOnClickListener(this);
        btn_read_code_tc.setOnClickListener(this);
        btn_recharge_tc.setOnClickListener(this);
        btn_keyi_szt.setOnClickListener(this);
        btn_keyi_tc.setOnClickListener(this);
        btn_change_app_szt.setOnClickListener(this);
        btn_change_app_tc.setOnClickListener(this);
        btn_duandian.setOnClickListener(this);
        btn_action.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        hasConnected = InitializeUtil.getInstance(mContext).isHasConnected();
        count = 0;
        httpT = 0;
        switch (v.getId()) {
            case R.id.btn_init://初始化
                init();
                break;
            case R.id.btn_reset://重置
                toReset();
                break;
            case R.id.btn_seid://获取seid
                initSeid();
//                setReset();
                break;
            case R.id.btn_send://下载apdu-szt
                setBtnClick(false);
                downloadApduSZT();
                break;
            case R.id.btn_create_ssd://创建SSD-szt
                setBtnClick(false);
                createSSD_SZT();
                break;
            case R.id.btn_send_tc://下载apdu-tc
                setBtnClick(false);
                downloadApduTC();
                break;
            case R.id.btn_create_ssd_tc://创建SSD-tc
                setBtnClick(false);
                createSSD_TC();
                break;
            case R.id.btn_create_ssd_bj://创建北京SSD
                setBtnClick(false);
                createSSD_BJ();
                break;
            case R.id.btn_apdu_bj://下载北京apdu
                setBtnClick(false);
                downloadApduBJ();
                break;
            case R.id.btn_read_code://读取卡号 00 B0 95 0C 08
                getCode();
                break;
            case R.id.btn_recharge_szt://深圳通充值
                setBtnClick(false);
                toRecharge(TYPE_SZT, URL_TYPE_PERSONALIZE);
                break;
            case R.id.btn_read_code_tc://太仓读卡
                getTCCode();
                break;
            case R.id.btn_recharge_tc://太仓充值
                setBtnClick(false);
                toRecharge(TYPE_TC, URL_TYPE_PERSONALIZE);
                break;
            case R.id.btn_keyi_szt://深圳通可疑交易检测
                setBtnClick(false);
                toRecharge(TYPE_SZT, URL_TYPE_KEYI);
                break;
            case R.id.btn_keyi_tc://太仓可疑交易检测
                setBtnClick(false);
                toRecharge(TYPE_TC, URL_TYPE_KEYI);
                break;
            case R.id.btn_change_app_szt://切换应用到深圳通
                break;
            case R.id.btn_change_app_tc://切换应用到太仓
                break;
            case R.id.btn_close://关闭
                toClose();
                break;
            case R.id.btn_duandian:
//                toDuandian();
                stopService(new Intent(MainActivity.this, ApduService.class));
                break;
            case R.id.btn_change://模式切换（只有为进行过模式切换的机器才会用到）
//                change();

                break;
            case R.id.btn_reset_apdu://重置芯片
                resetAll();
                break;
            case R.id.btn_action:
//                setBtnClick(false);
//                httpT = 1;
//                initHttp();
                sendBroad();
                break;
            default:
                break;
        }
    }

    private void sendBroad() {
        Intent intent = new Intent();
        intent.setAction(ApduService.APDUSERVICE_ACTION);
        sendBroadcast(intent);
    }

    private void toDuandian() {
        int[] results = m_api_msg.mstarc_sle97_write_buf(0x1B05, new int[]{0, 0});    //power off
        startLog("断电：", results + "");
        if (results != null) {
            logIntArray(results, "断电结果：");
        }
    }

    private void setBtnClick(boolean clickable) {
        resetAllBtnClick(clickable);
    }

    private void resetAllBtnClick(boolean clickable) {
        btn_init.setClickable(clickable);
        btn_reset.setClickable(clickable);
        btn_send.setClickable(clickable);
        btn_close.setClickable(clickable);
        btn_change.setClickable(clickable);
        btn_seid.setClickable(clickable);
        btn_create_ssd.setClickable(clickable);
        btn_personalize.setClickable(clickable);
        btn_create_ssd_tc.setClickable(clickable);
        btn_send_tc.setClickable(clickable);
        btn_read_code.setClickable(clickable);
        btn_reset_apdu.setClickable(clickable);
        btn_create_ssd_bj.setClickable(clickable);
        btn_apdu_bj.setClickable(clickable);
        btn_recharge_szt.setClickable(clickable);
        btn_read_code_tc.setClickable(clickable);
        btn_recharge_tc.setClickable(clickable);
        btn_keyi_szt.setClickable(clickable);
        btn_keyi_tc.setClickable(clickable);
        btn_change_app_szt.setClickable(clickable);
        btn_change_app_tc.setClickable(clickable);
        btn_duandian.setClickable(clickable);
        btn_action.setClickable(clickable);
    }

    private boolean toActivationFirst(String aid) {
        int[] params = StringAndByteUtil.getInt("80F001000B4F095" + aid);
        int[] results = ApduUtil.apdu(m_api_msg, params);
        if (isSucceed(results)) {
            return true;
        }
        startLog("激活第一个应用：", "失败！");
        return false;
    }

    private void toActivationSecond(String aidFirst, String aidSecond) {
        if (toSelectCRS()) {
            if (toActivationFirst(aidFirst)) {
                int[] params = StringAndByteUtil.getInt("80F001010B4F095" + aidSecond);
                int[] results = ApduUtil.apdu(m_api_msg, params);
                if (isSucceed(results)) {
                    startLog("切换最终结果：", "成功！");
                }
            }
        }
    }

    private boolean toSelectCRS() {
        int[] params = StringAndByteUtil.getInt("00A4040009A00000015143525300");
        int[] results = ApduUtil.apdu(m_api_msg, params);
        if (isSucceed(results)) {
            startLog("选择CRS第一步：", "成功！");
            params = StringAndByteUtil.getInt("6F168409A00000015143525300");
            results = ApduUtil.apdu(m_api_msg, params);
            if (isSucceed(results)) {
                startLog("选择CRS第二步：", "成功！");
                params = StringAndByteUtil.getInt("A5099F0802010080020003");
                results = ApduUtil.apdu(m_api_msg, params);
                if (isSucceed(results)) {
                    startLog("选择CRS第三步：", "成功！");
                    return true;
                }
                startLog("选择CRS第三步：", "失败！");
            } else {
                startLog("选择CRS第二步：", "失败！");
            }
        } else {
            startLog("选择CRS第一步：", "失败！");
        }
        return false;
    }

    /**
     * 太仓读卡
     */
    private void getTCCode() {
        /*======选择应用======*/
        int[] params = StringAndByteUtil.getInt("00A4040010A0000005980000051200000200000001");
        int[] results = ApduUtil.apdu(m_api_msg, params);
        if (results != null)
            logIntArray(results, "chooseApp1：");
        results = is0x61(results);
        if (results != null)
            logIntArray(results, "chooseApp2：");
        if (!isSucceed(results)) {
            return;
        }
        params = StringAndByteUtil.getInt("00A40000023F00");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "file1结果1：");
        }
        results = is0x61(results);
        if (results != null) {
            logIntArray(results, "file1结果2：");
        }
        params = StringAndByteUtil.getInt("00A40000023F01");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "file2结果1：");
        }
        results = is0x61(results);
        if (results != null) {
            logIntArray(results, "file2结果2：");
        }
        params = StringAndByteUtil.getInt("00B0950202");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "选择城市结果：");
        }
        if (isSucceed(results)) {
            String cityStr = StringAndByteUtil.intArrayToHexString(results);
            mCity = cityStr.substring(0, cityStr.length() - 4);
        } else {
            return;
        }
        params = StringAndByteUtil.getInt("00B0950C08");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "读卡1结果：");
        }
//        params = StringAndByteUtil.getInt("00B095001E");
//        results = ApduUtil.apdu(m_api_msg, params);
//        if (results != null) {
//            logIntArray(results, "读卡2结果1：");
//        }
//        params = StringAndByteUtil.getInt("00B0950A0A");
//        results = ApduUtil.apdu(m_api_msg, params);
//        if (results != null) {
//            logIntArray(results, "读卡2结果2：");
//        }
        getFinallyCodeTC(results);
        params = StringAndByteUtil.getInt("805C000204");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "余额1结果：");
        }
        if (isSucceed(results)) {
            String blalanceStr = StringAndByteUtil.intArrayToHexString(results);
            mBalance = blalanceStr.substring(2, blalanceStr.length() - 4);
            mBalance = Integer.parseInt(mBalance, 16) + "";
            startLog("余额：", mBalance);
        }
        /*====================↓↓↓↓消费记录↓↓↓↓=======================*/
//        params = StringAndByteUtil.getInt("00A40000020018");
//        results = ApduUtil.apdu(m_api_msg, params);
//        if (results != null) {
//            logIntArray(results, "消费记录1结果：");
//        }
//        for (int i = 0x01; i <= 0x0A; i++) {
//            String iStr = i + "";
//            if (i < 10) {
//                iStr = "0" + i;
//            }
//            startLog("iStr：", iStr);
//            params = StringAndByteUtil.getInt("00B2" + iStr + "0417");
//            results = ApduUtil.apdu(m_api_msg, params);
//            if (results != null) {
//                logIntArray(results, (i + 1) + "消费记录2结果：");
//            }
//            if (results.length >= 2 && results[results.length - 2] == 0x6A && results[results.length - 1] == 0x83) {
//                break;
//            }
//        }
//        params = StringAndByteUtil.getInt("00A40000020010");
//        results = ApduUtil.apdu(m_api_msg, params);
//        if (results != null) {
//            logIntArray(results, "异地消费记录1结果：");
//        }
//        for (int i = 0x01; i <= 0x0A; i++) {
//            String iStr = i + "";
//            if (i < 10) {
//                iStr = "0" + i;
//            }
//            startLog("iStr：", iStr);
//            params = StringAndByteUtil.getInt("00B2" + iStr + "0417");
//            results = ApduUtil.apdu(m_api_msg, params);
//            if (results != null) {
//                logIntArray(results, (i + 1) + "异地消费记录2结果：");
//            }
//            if (results.length >= 2 && results[results.length - 2] == 0x6A && results[results.length - 1] == 0x83) {
//                break;
//            }
//        }
        /*=========================↑↑↑↑消费记录↑↑↑↑================================*/
        params = StringAndByteUtil.getInt("00A4000002001A");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "读取充值记录1结果：");
        }
        params = StringAndByteUtil.getInt("00B2010417");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "最后一条充值记录1结果：");
        }
        mLastRecord = StringAndByteUtil.intArrayToHexString(results);
    }

    private boolean isSucceed(int[] result) {
        if (result != null && result.length >= 2 && result[result.length - 2] == 0x90 && result[result.length - 1] == 0x00) {
            return true;
        }
        return false;
    }

    private void getFinallyCodeTC(int[] results) {
        if (results != null && results.length >= 2 && results[results.length - 2] == 0x90 && results[results.length - 1] == 0x00) {
            mCode = StringAndByteUtil.intArrayToHexString(results);
            mCode = mCode.substring(0, mCode.length() - 4);
        }
    }

    /**
     * 北京apdu下载
     */
    private void downloadApduBJ() {
        isPersonalize = false;
        if (!hasConnected) {
            return;
        }
        if (checkSeid()) {
            requestTypeEnum = RequestTypeEnum.GET_APDU;
            URL = APDU_URL;
            mType = getType(TYPE_BJ);
            startHttp(URL + getFirstRequest(), 1);
        } else {
            Toast.makeText(mContext, "请先读取seid", Toast.LENGTH_SHORT).show();
        }
    }

    private void createSSD_BJ() {
        isPersonalize = false;
        if (checkSeid()) {
            requestTypeEnum = RequestTypeEnum.CREATE_SSD;
            URL = SSD_URL;
            mType = getType(TYPE_BJ);
            startHttp(URL + getFirstRequest(), 1);
        } else {
            Toast.makeText(mContext, "请先读取seid", Toast.LENGTH_SHORT).show();
        }
    }

    private void toKeyi() {
        URL = KEYI_URL;
    }

    /**
     * 充值的网路请求
     *
     * @param type
     */
    private void toRecharge(int type, int urlType) {
        mType = getType(type);
        String codeStr = "";
        switch (type) {
            case TYPE_SZT:
                getCode();
                codeStr = mCode;
                break;
            case TYPE_TC:
                getTCCode();
                codeStr = mCity + mCode;
                break;
        }
        isPersonalize = true;
        if (urlType == URL_TYPE_PERSONALIZE) {
            URL = PERSONALIZE_URL + getRechargeStr(codeStr);
        } else {
            URL = KEYI_URL + getRechargeStr(codeStr);
        }
        startHttp(URL + FIRSTREQUESTSTR, 1);
    }

    private String getRechargeStr(String codeStr) {
        return APPSERIAL + codeStr + BALANCE + mBalance + CHARGECOUNT + LASTRECORD + mLastRecord;
    }

    /**
     * 模式切换（只用未进行过模式切换的机器用到）
     */
    private void change() {
        if (!hasConnected) {
            return;
        }
        int[] nfc_buf1 = SwitchModeUtil.switchMode(m_api_msg);
        tv_res.setText((nfc_buf1 == null) ? "失败" : "成功," + BytetohexStringUtil.BytetohexString(nfc_buf1));
        logIntArray(nfc_buf1, "模式切换：");
    }

    /**
     * 关闭nfc
     */
    private void toClose() {
        if (!hasConnected) {
            return;
        }
        int res = CloseUtil.closeMstarcApi(m_api_msg);
        tv_res.setText((res == 0) ? "关闭成功" : "关闭失败");
        startLog("关闭：", res + "");
    }

    /**
     * 创建太仓的SSD
     */
    private void createSSD_TC() {
        isPersonalize = false;
        if (checkSeid()) {
            requestTypeEnum = RequestTypeEnum.CREATE_SSD;
            URL = SSD_URL;
            mType = getType(TYPE_TC);
            startHttp(URL + getFirstRequest(), 1);
        } else {
            Toast.makeText(mContext, "请先读取seid", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 下载太仓的apdu包
     */
    private void downloadApduTC() {
        if (!hasConnected) {
            return;
        }
        isPersonalize = false;
        if (checkSeid()) {
            requestTypeEnum = RequestTypeEnum.GET_APDU;
            URL = APDU_URL;
            mType = getType(TYPE_TC);
            startHttp(URL + getFirstRequest(), 1);
        } else {
            Toast.makeText(mContext, "请先读取seid", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 创建深圳通的SSD
     */
    private void createSSD_SZT() {
        isPersonalize = false;
        if (checkSeid()) {
            requestTypeEnum = RequestTypeEnum.CREATE_SSD;
            URL = SSD_URL;
            mType = getType(TYPE_SZT);
            startHttp(URL + getFirstRequest(), 1);
        } else {
            Toast.makeText(mContext, "请先读取seid", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 下载深圳通的apdu包
     */
    private void downloadApduSZT() {
        if (!hasConnected) {
            return;
        }
        isPersonalize = false;
        if (checkSeid()) {
            requestTypeEnum = RequestTypeEnum.GET_APDU;
            URL = APDU_URL;
            mType = getType(TYPE_SZT);
            startHttp(URL + getFirstRequest(), 1);
        } else {
            Toast.makeText(mContext, "请先读取seid", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取seid
     */
    private void initSeid() {
        int[] nfc_buf = InitSEIDUtil.initSEID(m_api_msg);
        if (nfc_buf != null) {
            logIntArray(nfc_buf, "Code:");
            seid = StringAndByteUtil.intArrayToHexString(getSEID(nfc_buf));
            tv_res.setText("SEID：" + seid);
            startLog("seidForHex：", seid);
        } else {

        }
    }

    /**
     * 重置nfc
     */
    private void toReset() {
        if (!hasConnected) {
            return;
        }
        int[] nfc_reset_buf = MstarcResetUtil.reset(m_api_msg);
        tv_res.setText((nfc_reset_buf == null) ? "失败" : "成功," + BytetohexStringUtil.BytetohexString(nfc_reset_buf));
        if (nfc_reset_buf != null)
            logIntArray(nfc_reset_buf, "重置:");
    }

    /**
     * 初始化nfc
     */
    private void init() {
        if (!hasConnected) {
            return;
        }
        int i_ret = MstarcInitUtil.init(m_api_msg);
        tv_res.setText((i_ret == 0) ? "初始化成功" : "初始化失败");
        startLog("初始化:", i_ret + "");
    }

    private void setReset() {
        int[] resetApdu = StringAndByteUtil.getInt("4442FFFF080D069EE93D9818FE");
        int[] resetResult1 = ApduUtil.apdu(m_api_msg, resetApdu);
        logIntArray(resetApdu, "重置步骤1参数：");
        if (resetResult1 != null)
            logIntArray(resetResult1, "重置结果1：");
        resetResult1 = MstarcResetUtil.reset(m_api_msg);
        startLog("重置步骤2：", "reset");
        if (resetResult1 != null)
            logIntArray(resetResult1, "重置结果2:");
        resetApdu = StringAndByteUtil.getInt("4442FFFF080D069EE93D9818FE");
        resetResult1 = ApduUtil.apdu(m_api_msg, resetApdu);
        logIntArray(resetApdu, "重置步骤3参数：");
        if (resetResult1 != null)
            logIntArray(resetResult1, "重置结果3：");
        resetApdu = StringAndByteUtil.getInt("4442010000");
        resetResult1 = ApduUtil.apdu(m_api_msg, resetApdu);
        logIntArray(resetApdu, "重置步骤4参数：");
        if (resetResult1 != null)
            logIntArray(resetResult1, "重置结果4：");
    }

    /**
     * 重置芯片
     */
    private void resetAll() {
        int[] resetApdu = StringAndByteUtil.getInt("4442FFFF080D069EE93D9818FE");
        int[] resetResult1 = ApduUtil.apdu(m_api_msg, resetApdu);
        logIntArray(resetApdu, "重置步骤1参数：");
        if (resetResult1 != null)
            logIntArray(resetResult1, "重置结果1：");
        int[] resetResult2 = MstarcResetUtil.reset(m_api_msg);
        startLog("重置步骤2：", "reset");
        if (resetResult2 != null)
            logIntArray(resetResult2, "重置结果2:");
        int[] resetResult3 = ApduUtil.apdu(m_api_msg, resetApdu);
        logIntArray(resetApdu, "重置步骤3参数：");
        if (resetResult3 != null)
            logIntArray(resetResult3, "重置结果3：");
        int[] resetApdu4 = StringAndByteUtil.getInt("4442010000");
        int[] resetResult4 = ApduUtil.apdu(m_api_msg, resetApdu4);
        logIntArray(resetApdu4, "重置步骤4参数：");
        if (resetResult4 != null)
            logIntArray(resetResult4, "重置结果4：");
        int[] resetApdu5 = StringAndByteUtil.getInt("444202000100");
        int[] resetResult5 = ApduUtil.apdu(m_api_msg, resetApdu5);
        logIntArray(resetApdu5, "重置步骤5参数：");
        if (resetResult5 != null)
            logIntArray(resetResult5, "重置结果5：");
        int[] resetResult6 = MstarcResetUtil.reset(m_api_msg);
        startLog("重置步骤6：", "reset");
        if (resetResult6 != null)
            logIntArray(resetResult6, "重置结果6:");
    }

    /**
     * 获取卡号
     * 获取最后一条交易记录
     */
    private void getCode() {
        /*======选择应用======*/
        int[] params = StringAndByteUtil.getInt("00A404000E535A542E57414C4C45542E454E56");
        int[] results = ApduUtil.apdu(m_api_msg, params);
        if (results != null)
            logIntArray(results, "chooseApp：");
        /*======选择文件1======*/
        params = StringAndByteUtil.getInt("00A40000023F00");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null)
            logIntArray(results, "file1：");
        results = is0x61(results);
        /*======选择文件2======*/
        params = StringAndByteUtil.getInt("00A40000021001");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null)
            logIntArray(results, "file2：");
        results = is0x61(results);
        /*======读取卡号======*/
        params = StringAndByteUtil.getInt("00B0950C08");
        results = ApduUtil.apdu(m_api_msg, params);
        logIntArray(params, "读取卡号参数：");
        if (results != null)
            logIntArray(results, "卡号结果：");
        mCode = StringAndByteUtil.intArrayToHexString(results);
        getFinallyCode(results);
        /*======读取余额======*/
        params = StringAndByteUtil.getInt("805C000204");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null)
            logIntArray(results, "余额：");
        if (results.length > 2 && results[results.length - 2] == 0x90 && results[results.length - 1] == 0x00) {
            mBalance = StringAndByteUtil.intArrayToHexString(results);
            mBalance = mBalance.substring(2, mBalance.length() - 4);
            mBalance = Integer.parseInt(mBalance, 16) + "";
            startLog("余额：", mBalance);
        }
        /*======读取交易记录======*/
        params = StringAndByteUtil.getInt("00A40000020018");
        results = ApduUtil.apdu(m_api_msg, params);
        if (results != null) {
            logIntArray(results, "交易记录1：");
        }
        params = StringAndByteUtil.getInt("00B201C400");
        results = ApduUtil.apdu(m_api_msg, params);
        logIntArray(params, "最后一条交易记录参数1：");
        if (results != null) {
            logIntArray(results, "最后一条交易记录结果1：");
        }
        if (is0x6c(results)) {
            params[params.length - 1] = results[results.length - 1];
            results = ApduUtil.apdu(m_api_msg, params);
        }
        logIntArray(params, "最后一条交易记录参数2：");
        if (results != null) {
            logIntArray(results, "最后一条交易记录结果2：");
        }
        mLastRecord = StringAndByteUtil.intArrayToHexString(results);
    }

    private int[] nextResult(int[] result) {
        secondApdu[secondApdu.length - 1] = result[result.length - 1];
        int[] nextResult = ApduUtil.apdu(m_api_msg, secondApdu);
        if (nextResult != null) {
            logIntArray(nextResult, "第二次请求结果：");
        } else {
            startLog("结果：", "为空！");
        }
        return nextResult;
    }

    private boolean is0x61BL(int[] result) {
        if (result.length >= 2 && result[result.length - 2] == 0x61) {
            return true;
        }
        return false;
    }

    private int[] is0x61(int[] result) {
        if (result.length >= 2 && result[result.length - 2] == 0x61) {
            result = nextResult(result);
        }
        return result;
    }

    private boolean is0x6c(int[] result) {
        if (result[result.length - 2] == 0x6c) {
            return true;
        }
        return false;
    }

    /**
     * 进行卡号的处理，处理成需要的十进制字符串
     *
     * @param code
     */
    private void getFinallyCode(int[] code) {
        if (code[code.length - 2] == 0x90 && code[code.length - 1] == 0x00) {
            mCode = mCode.substring(8, mCode.length() - 4);
            startLog("截取之后的卡号：", mCode);
            int[] codeBtyes = StringAndByteUtil.getInt(mCode);
            logIntArray(codeBtyes, "截取之后的卡号数组：");
            int[] finallyBytes = new int[codeBtyes.length];
            for (int i = 0; i < codeBtyes.length; i++) {
                finallyBytes[i] = codeBtyes[codeBtyes.length - (i + 1)];
            }
            logIntArray(finallyBytes, "小端转换之后的卡号数组：");
            mCode = StringAndByteUtil.intArrayToHexString(finallyBytes);
            startLog("最终十六进制的卡号：", mCode);
            mCode = Integer.parseInt(mCode, 16) + "";
            startLog("最终的十进制卡号：", mCode);
        }
    }

    /**
     * 拼接第一次请求借口
     *
     * @return
     */
    private String getFirstRequest() {
        return FIRSTREQUESTSTR + setSeid();
    }

    /**
     * 拼接seid
     *
     * @return
     */
    private String setSeid() {
        return SEID_STR + seid;
    }

    /**
     * 获取拼接接口的类型（深圳通、太仓）
     *
     * @param type
     * @return
     */
    private String getType(int type) {
        mTypeInt = type;
        switch (type) {
            case TYPE_SZT:
                return TYPE + SZT;
            case TYPE_TC:
                return TYPE + TC;
            case TYPE_BJ:
                return TYPE + BJ;
            default:
                return "";
        }
    }

    /**
     * 检测是否已经获取了seid
     *
     * @return
     */
    private boolean checkSeid() {
        if (!seid.equals(""))
            return true;
        return false;
    }

    /**
     * 将获取的seid进行处理
     *
     * @param nfc_buf
     * @return
     */
    private int[] getSEID(int[] nfc_buf) {
        int[] seids = new int[nfc_buf.length - 4];
        if (nfc_buf.length > 4) {
            for (int i = 0; i < seids.length; i++) {
                seids[i] = nfc_buf[i + 2];
            }
        }
        return seids;
    }

    /**
     * 进行网络请求
     *
     * @param httpUrl
     * @param msgFlg
     */
    private void startHttp(String httpUrl, int msgFlg) {
        httpUrl = httpUrl + mType;
        Log.d(TAG, (count + 1) + "：" + "secondUrl: " + httpUrl);
        startRequest(httpUrl, msgFlg);
    }

    private void logIntArray(int[] intArray, String tagTitle) {
        LogUtil.logIntArray(intArray, tagTitle);
    }

    private void startLog(String logTitle, String logContent) {
        LogUtil.startLog(logTitle, logContent);
    }

    @Override
    public void requestJsonOnSucceed(String json, int msgFlag) {
        super.requestJsonOnSucceed(json, msgFlag);
        switch (msgFlag) {
            case 1:
            case 2:
                goToNext(json, msgFlag);
                break;
        }
    }

    private void goToNext(String json, int msgFlag) {
        apduSum = 0;
        count++;
        lastData = "";
        lastApduSw = new int[2];
        Log.d(TAG, count + "：" + "requestJsonOnSucceed: " + json);
        int[] result = new int[0];
        ApduEntity apduEntity = getTByJsonString(json, ApduEntity.class);
        if (apduEntity != null && apduEntity.getApduList() != null && apduEntity.getApduList().size() != 0) {
            int removeCount = 0;
            for (int i = 0; i < apduEntity.getApduList().size(); i++) {
                String lastApdu = apduEntity.getApduList().get(i);
//                if (mLastApdu.equals("00B0950000")) {
//                    mLastApdu = "00B0950020";
//                }
//                if (mLastApdu.equals("00B09A0000")) {
//                    mLastApdu = "00B09A001C";
//                }
                result = ApduUtil.apdu(m_api_msg, StringAndByteUtil.getInt(lastApdu));
                logIntArray(StringAndByteUtil.getInt(lastApdu), count + "：" + "条数：" + (i + 1) + "参数1：");
                if (result != null) {
                    logIntArray(result, count + "：" + "条数：" + (i + 1) + "结果1：");
                }
                if (is0x61BL(result)) {
                    secondApdu[secondApdu.length - 1] = result[result.length - 1];
                    logIntArray(secondApdu, count + "：" + "条数：" + (i + 1) + "参数2：");
                    result = ApduUtil.apdu(m_api_msg, secondApdu);
//                    removeCount = 2;
                    result = is0x61(result);
                    if (result != null) {
                        logIntArray(result, count + "：" + "条数：" + (i + 1) + "结果2：");
                    }
                }
                if (is0x6c(result)) {
                    int[] params = StringAndByteUtil.getInt(lastApdu);
                    params[params.length - 1] = result[result.length - 1];
                    logIntArray(params, count + "：" + "条数：" + (i + 1) + " 6c参数：");
                    result = ApduUtil.apdu(m_api_msg, params);
                    if (result != null) {
                        logIntArray(result, count + "：" + "条数：" + (i + 1) + "6c结果：");
                    }
                }
                if (isPersonalize && mTypeInt == TYPE_SZT) {
                    lastData += StringAndByteUtil.intArrayToHexString(getResultData(result, removeCount)) + ";";
                } else {
                    lastData = StringAndByteUtil.intArrayToHexString(getResultData(result, removeCount));
                }
                mLastApdu = apduEntity.getApduList().get(i);
                if (result.length >= 2 && result[result.length - 2] == 0x90 && result[result.length - 1] == 0x00) {
                    apduSum++;
                } else {
                    break;
                }
            }
            if (result.length >= 2) {
                lastApduSw[0] = result[result.length - 2];
                lastApduSw[1] = result[result.length - 1];
                String url1 = "";
                if (isPersonalize && mTypeInt == TYPE_SZT) {
                    lastData = lastData.substring(0, lastData.length() - 1);
                }
                startLog("mLastApdu：", mLastApdu);
                if (httpT == 1) {
                    initHttp();
                } else {
                    url1 = URL + "&lastApduSw=" + StringAndByteUtil.intArrayToHexString(lastApduSw)
                            + "&lastData=" + lastData
                            + "&apduSum=" + apduSum
                            + LASTAPDU + mLastApdu
                            + setSeid();
                    startHttp(url1, 1);
                }
            } else {
                Log.d(TAG, "请求结果为空！");
            }
        } else {
            setBtnClick(true);
//            if (apduEntity.isIsOk()) {
//                startLog("请求状态：", "请求结束！");
//            } else {
//                startLog("请求状态：", "请求失败！");
//            }
        }
    }

    private int[] getResultData(int[] data, int removeCount) {
        if (data.length >= removeCount) {
            int[] datas = new int[data.length - removeCount];
            for (int i = 0; i < datas.length; i++) {
                datas[i] = data[i];
            }
            return datas;
        }
        return new int[0];
    }

    private String getHttpParams(RequestTypeEnum typeEnum) {
        switch (typeEnum) {
            case CREATE_SSD:
                return "";
            case GET_APDU:
                return "";
            default:
                return "";
        }
    }

    @Override
    public void requestJsonOnError(int msgFlag) {
        super.requestJsonOnError(msgFlag);
        Log.d(TAG, "requestJsonOnError: ");
        setBtnClick(true);
    }

    @Override
    public void requestJsonOnLocalError(int msgFlag) {
        super.requestJsonOnLocalError(msgFlag);
        Log.d(TAG, "requestJsonOnLocalError: ");
        setBtnClick(true);
    }


    enum RequestTypeEnum {
        CREATE_SSD,
        GET_APDU
    }

    private void initHttp() {
//        toReset();
        if (seid.equals("")) {
            initSeid();
        }
        URL = IP1
                + SEID_STR + seid
                + LASTAPDU + mLastApdu
                + LASTDATA + lastData
                + APDUNUM + apduSum
                + LASTAPDUSW + StringAndByteUtil.intArrayToHexString(lastApduSw);
        startLog("URL：", URL);
        startRequest(URL, 2);
    }
}
